package org.openkoala.koala.popup;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;

public abstract class BaseAction implements IObjectActionDelegate {
	
	protected Shell shell;

	protected IWorkbenchPart targetPart;
	
	/**
	 * 获取当前选中的文件的路径
	 * 
	 * @return
	 */
	protected IResource getResource() {
		IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
		if (window != null) {
			IStructuredSelection selection = (IStructuredSelection) targetPart.getSite().getSelectionProvider().getSelection();
			Object element = selection.getFirstElement();
			IResource resources = null;
			if (element instanceof IResource) {
				resources = (IResource) element;
			}
			if (!(element instanceof IAdaptable)) {
				return null;
			}
			IAdaptable adaptable = (IAdaptable) element;
			Object adapter = adaptable.getAdapter(IResource.class);
			resources = (IResource) adapter;
			return resources;
		}
		return null;
	}
	
	/**
	 * 弹出框提示出错信息
	 * @param errorMessage
	 */
	public void popupErrorMessage(String errorMessage) {
		MessageBox messageBox = new MessageBox(shell, SWT.ICON_ERROR);
		messageBox.setMessage(errorMessage);
		messageBox.open();
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
	}

	@Override
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();  
        this.targetPart = targetPart;
	}
}
